/**
 * Copyright (c) 2011-9-23 WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.wkm.definition;

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * SystemLibraryPath 设置虚拟机的Library路径
 * @version 1.0 2011-12-30
 * @author WUKUNMENG
 */
public class SystemLibraryPath {

	//java.library.path值存放在JDK内的变量
	private static String PATH_NAME = "usr_paths";
	
	private static Logger logger = LoggerFactory.getLogger(SystemLibraryPath.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	/**
	 * 添加Library路径。由于JDK不支持java.library.path变量的
	 * 动态配置。在此可以实现动态更改java.library.path的值。
	 * 此处应用了java的反射机制！
	 * @param path 添加的新library 路径
	 */
	public static void addLibraryPath(String path){
		try{
			Field field = ClassLoader.class.getDeclaredField(PATH_NAME);
			field.setAccessible(Boolean.TRUE);
			String[] paths = (String[])field.get(null);
			String[] userPaths = null;
			if(paths == null || paths.length == 0){
				userPaths = new String[1];
			} else {
				
				//如果存在，就不在多此一举了
				for(String pth: paths){
					if(path.equals(pth)){
						return ;
					}
				}
				
				userPaths = new String[paths.length + 1];
				System.arraycopy(paths, 0, userPaths, 0, paths.length);
			}
			logger.info("添加java.library.path:" + path);
			userPaths[userPaths.length - 1] = path;
			field.set(null, userPaths);
		} catch (NoSuchFieldException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (IllegalArgumentException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (IllegalAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (SecurityException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		} 
		
		
	}

}
